//
//  CZEmotionModel.swift
//  刷新控件
//
//  Created by Albert Zhu on 16/10/25.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit
import YYModel

class CZEmotionModel: NSObject {
    
    var id: String?
    var chs: String?
    var type = false
    var gif: String?
    var png: String?
    /// emoji的十六进制编码
    var code: String? {
        didSet {
            guard let code = code else {return}
            
            let scanner = Scanner(string: code)
            var result: UInt32 = 0
            scanner.scanHexInt32(&result)
            
            guard let scalar = UnicodeScalar(result) else {return}
            
            emoji = String(Character(scalar))
        }
    }
    var emoji: String?
    var image: UIImage? {
        if type {return nil}
        
        guard let id = id,
            let png = png,
            let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil),
            let bundle = Bundle(path: path) else {return nil}
        
        return UIImage.init(named: "\(id)/\(png)", in: bundle, compatibleWith: nil)
    }
    
    // 表情使用次数
    var times: Int = 0

    override var description: String {
        return yy_modelDescription()
    }
    
    /// 通过表情的文本替换为表情图片
    ///
    /// - parameter font: 文本的字号
    ///
    /// - returns: 替换成图片的属性文本
    func imageText(font: UIFont) -> NSAttributedString {
        guard let image = image else {return NSAttributedString(string: "")}
        
        let attachment = CZEmotionAttachment()
        attachment.chs = chs
        attachment.image = image
        let height = font.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
        
        let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        
        // FIXME: - 设置文本字体属性，因为添加图片后，系统不会自动为其添加文本的属性，结果会导致计算行高错误，造成后面的字符和图片变小
        attr.addAttributes([NSFontAttributeName:font], range: NSRange(location: 0, length: 1))
        
        return attr
    }
}
